package com.fzy.core.validators;

import com.opensymphony.xwork.ActionContext;
import com.opensymphony.xwork.util.LocalizedTextUtil;
import com.opensymphony.xwork.util.OgnlValueStack;
import com.opensymphony.xwork.util.TextParseUtil;
import com.opensymphony.xwork.validator.DelegatingValidatorContext;
import com.opensymphony.xwork.validator.ValidationException;
import com.opensymphony.xwork.validator.validators.FieldValidatorSupport;

public class RequiredStringValidator extends FieldValidatorSupport {

	private boolean doTrim = true;

	public void setTrim(boolean trim) {
		doTrim = trim;
	}

	public boolean getTrim() {
		return doTrim;
	}

	public void validate(Object object) throws ValidationException {
		String fieldName = getFieldName();
		Object value = this.getFieldValue(fieldName, object);

		if (!(value instanceof String)) {
			addFieldError(fieldName, object);
		} else {
			String s = (String) value;

			if (doTrim) {
				s = s.trim();
			}

			if (s.length() == 0) {
				addFieldError(fieldName, object);
			}
		}
	}

	public String getMessage(Object object) {
        
        String name = getValidatorContext().getText(getFieldName());
        String message = getValidatorContext().getText("error.required", new String[]{name});;
//        Object action = ActionContext.getContext().getActionInvocation().getAction();
//        OgnlValueStack stack = ActionContext.getContext().getValueStack();
//        boolean pop = false;
//
//        if (!stack.getRoot().contains(object)) {
//            stack.push(object);
//            pop = true;
//        }
//
//        stack.push(this);
//
//        if (messageKey != null) {
//            if ((defaultMessage == null) || (defaultMessage.trim().equals(""))) {
//                defaultMessage = messageKey;
//            }
//            if ( getValidatorContext() == null) {
//                setValidatorContext(new DelegatingValidatorContext(object));
//            }
//            message = getValidatorContext().getText(messageKey, defaultMessage);
//        } else {
//            message = defaultMessage;
//        }
//
//        message = TextParseUtil.translateVariables(message, stack);
//
//        stack.pop();
//
//        if (pop) {
//            stack.pop();
//        }

        return message;
	}
	
}
